<?php

namespace App\Http\Controllers\App;

use App\Exceptions\FailException;
use App\Http\Controllers\Controller;
use App\Http\Services\CardOrderService;
use App\Models\Member;
use App\Models\MemberOrder;
use App\Models\MemberRechargeCardOrder;
use App\Models\Store;
use App\Models\StoreRecommendMember;
use App\Tool\Util;
use Carbon\Carbon;
use DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use mysql_xdevapi\Exception;
use Yansongda\LaravelPay\Facades\Pay;

class MemberOrderController extends Controller
{
    const COUPON_MONEY = "coupon_money";

    public function orderList()
    {
        $time = \request('time');
        $lon = \request('lon', 0);
        $let = \request('let', 0);
        $model = MemberOrder::select(['member_order.is_pay', 'member_order.pay_time', 'member_order.money', 's.name', 's.logo', 's.score', 's.area', DB::raw(Store::distance($lon, $let))])
            ->where('member_order.member_id', Auth::id())
            ->leftJoin('store as s', 's.id', '=', 'member_order.store_id')
            ->orderByDesc('member_order.created_at');
        if ($time == 'yd') {
            $model->whereDate('member_order.created_at', Carbon::yesterday());
        } elseif ($time == '7') {
            $model->whereDate('member_order.created_at', '>', Carbon::today()->subDay(7));
        } elseif ($time == 'month') {
            $model->whereDate('member_order.created_at', '>', Carbon::today()->subDay(30));
        } else {
            $model->whereDate('member_order.created_at', '=', Carbon::today());
        }
        $list = $model->paginate();
        return $list;
    }

    // region todo 订单页面展示数据
    public function getOrderNew(Request $request)
    {
        $this->validate($request, [
            'store_id' => 'required|numeric',
            'money' => 'required',
        ], [
            "store_id.required" => "store_id不能为空",
            "store_id.numeric" => "store_id必须是数字",
            "money.required" => "money不能为空",
        ]);

        // 商家优惠
        $store_id = $request->input("store_id");
        $store = Store::whereId($store_id)->where("is_close", 1)->first();
        if (!$store) {
            throw new FailException("店铺已经关闭");
        }

        $money = $request->input("money");

        // 会员折扣
        $member = Auth::user();

        $card_money_coupon = $member->card_money_coupon; // 会员折扣金额
        if ($card_money_coupon == 0) {
            // todo 会员折扣金额等于0，就没有优惠
            $discount_amount = 0;
            $actual_amount = $money;
            $card_money_coupon = $member->card_money_coupon;
            $surplus_card_money_coupon = 0;
        } elseif ($card_money_coupon < bcmul($money, $store->discount, 0)) {
            // todo 会员优惠金额存在， 但是小于店家优惠金额
            $discount_amount = $member->card_money_coupon;
            $actual_amount = $money - $discount_amount; // 实际支付金额
            $surplus_card_money_coupon = 0;
            $card_money_coupon = 0;

        } else {

            // todo 会员优惠金额大于 店家给的优惠金额
            $discount_amount = bcmul($money, $store->discount, 0); // 优惠金额
            $actual_amount =  $money - $discount_amount; // 实际支付金额
            $surplus_card_money_coupon = $card_money_coupon - $discount_amount; // 剩余优惠金额
            $card_money_coupon = $member->card_money_coupon; // 会员折扣金额
        }

        return $this->renderJson([
            "store_id" => $store_id,  // 商家id
            "discount" => $store->discount, // 商家折扣
            "card_money_coupon" => $card_money_coupon, // 会员折扣金额
            "card_money" => $member->card_money, // 会员余额支付
            "surplus_card_money_coupon" => $surplus_card_money_coupon, // 会员剩余优惠金额
            "money" => $money,   // 会员输入金额
            "discount_amount" => $discount_amount, // 优惠金额
            "actual_amount" => $actual_amount, // 实际支付金额

        ]);
    }

    // endregion


    // region  todo 会员购买下单
    public function consumePay(Request $request)
    {
        $this->validate($request, [
            'store_id' => "required|numeric",
            "money" => "required",
            'input_money' => 'required',
            "payment_type" => "required",// 1，支付宝支付，2微信支付， 3，余额支付

        ], [
            "store_id.required" => "store_id不能为空",
            "store_id.numeric" => "store_id必须是数字",
            "money.required" => "money不能为空",
            "input_money.required" => "input_money不能为空",
        ]);

        $order_no = Util::getOrderNum();
        $store_id = $request->input("store_id");
        $money = $request->input("money");
        $payment_type = $request->input("payment_type");
        $coupon_money = $request->input("coupon_money");
        $discount = $request->input('discount');
        $input_money = $request->input("input_money");  // 会员输入金额


        $member = Auth::user();

        //  计算金额是否正确
        $card_money_coupon = $member->card_money_coupon; // 会员折扣金额
        if ($card_money_coupon == 0) {
            // todo 会员折扣金额等于0，就没有优惠
            $actual_amount = $input_money;

        } elseif ($card_money_coupon < bcmul($input_money, $discount, 0)) {
            // todo 会员优惠金额存在， 但是小于店家优惠金额
            $discount_amount = $member->card_money_coupon;
            $actual_amount = $input_money - $discount_amount; // 实际支付金额

        } else {
            // todo 会员优惠金额大于 店家给的优惠金额
            $amount =   bcmul($input_money, $discount, 0);
            $actual_amount = $input_money-$amount ; // 实际支付金额

        }

        $member_order = new  MemberOrder();
        $member_order->order_no = $order_no;
        $member_order->member_id = Auth::id();
        $member_order->store_id = $store_id;
        $member_order->money = $money;
        $member_order->payment_type = $payment_type;
        $member_order->input_money = $input_money;

        try {
            $params = [];
            switch ($request->input("payment_type")) {
                case "余额支付":
                    $member_order->is_pay = 1; // 余额直接支付
                    $member_order->pay_time = Carbon::now();
                    // 订单记录
                    $member_order->save();
                    $order = new MemberOrder();
                    $order->memberPayCommission($store_id, $money, $member_order->id, Auth::id());
                    // 扣除余额

                    // 扣取卡金额
                    $member->decrement("card_money", $money);

                    break;
                case "微信支付":

                    if ($money != $actual_amount) {
                        throw new \Exception("折扣金额不正确");
                    }
                    $member_order->coupon_money = $coupon_money;
                    $member_order->discount = $discount;
                    $member_order->save();
                    $params = Pay::wechat()->app([
                        'body' => "充值",
                        'out_trade_no' => $order_no,
                        'total_fee' => $money * 100,
                        'attach' => 1,
                    ])->getContent();

                    break;
                case "支付宝支付宝":

                    if ($money != $actual_amount) {
                        throw new \Exception("折扣金额不正确");
                    }
                    $member_order->coupon_money = $coupon_money;
                    $member_order->discount = $discount;
                    $member_order->save();
                    $params = Pay::alipay()->app([
                        'body' => "充值",
                        'out_trade_no' => $order_no,
                        'total_fee' => $money,
                        'passback_params' => 1,    //业务类型
                    ])->getContent();
            }
            \DB::commit();

            if ($params) {
                return $this->renderJson(['payment_type' => $payment_type, 'params' => json_decode($params)]);
            } else {
                return $this->renderJson(['payment_type' => $payment_type, 'params' => $params]);
            }


        } catch (\Exception $exception) {
            \DB::rollBack();
            \Log::error($exception);
            throw  new FailException("下单失败！");
        }

    }

    // web支付
    public function consumeWebPay(Request $request)
    {

        $this->validate($request, [
            'store_id' => "required|numeric",
            "money" => "required",
            "payment_type" => "required",// 1，支付宝支付，2微信支付， 3，余额支付

        ], [
            "store_id.required" => "store_id不能为空",
            "store_id.numeric" => "store_id必须是数字",
            "money.required" => "money不能为空",
        ]);

        $order_no = Util::getOrderNum();
        $store_id = $request->input("store_id");
        $money = $request->input("money");
        $payment_type = $request->input("payment_type");
        $coupon_money = $request->input("coupon_money");

        $member_order = new  MemberOrder();
        $member_order->order_no = $order_no;
        $member_order->member_id = Auth::id();
        $member_order->store_id = $store_id;
        $member_order->money = $money;
        $member_order->payment_type = $payment_type;
        $member_order->coupon_money = $coupon_money;

        try {
            // 订单记录

            $params = [];
            switch ($request->input("payment_type")) {
                case "余额支付":
                    $member_order->is_pay = 1; // 余额直接支付
                    $member_order->pay_time = Carbon::now();
                    $member_order->save();
                    $order = new MemberOrder();
                    $order->memberPayCommission($store_id, $money, $member_order->id, Auth::id());
                    // 扣除余额
                    $member = Auth::user();
                    // 扣取卡金额
                    $member->decrement("card_money", $money);

                    break;
                case "微信支付":

                    //订单记录
                    $member_order->save();
                    $params = Pay::wechat()->wap([
                        'body' => "充值",
                        'out_trade_no' => $order_no,
                        'total_fee' => $money * 100,
                        'attach' => 3,
                    ])->getContent();

                    break;
                case "支付宝支付宝":

                    //订单记录
                    $member_order->save();
                    $params = Pay::alipay()->wap([
                        'body' => "充值",
                        'out_trade_no' => $order_no,
                        'total_fee' => $money,
                        'passback_params' => 3,    //业务类型
                    ])->getContent();
            }

            \DB::commit();
            if ($params) {
                return $this->renderJson(['payment_type' => $payment_type, 'params' => json_decode($params)]);
            } else {

                return $this->renderJson(['payment_type' => $payment_type, 'params' => $params]);
            }
        } catch (\Exception $exception) {
            \DB::rollBack();
            \Log::error($exception);
            throw  new FailException("下单失败！");
        }

    }

    // endregion

    //region  todo 购卡下单

    public function cardPay(Request $request)
    {
        $this->validate($request, [
            'store_id' => "required|numeric",
            "money" => "required",
            "payment_type" => "required",// 1，支付宝支付，2微信支付， 3，余额支付

        ], [
            "store_id.required" => "store_id不能为空",
            "store_id.numeric" => "store_id必须是数字",
            "money.required" => "money不能为空",
        ]);

        $order_no = Util::getOrderNum();
        $store_id = $request->input("store_id");
        $money = $request->input("money");
        $payment_type = $request->input("payment_type");

        $member_recharge_card_order = new MemberRechargeCardOrder();
        $member_recharge_card_order->order_no = $order_no;
        $member_recharge_card_order->member_id = Auth::id();
        $member_recharge_card_order->store_id = $store_id;
        $member_recharge_card_order->money = 3000;//$money;
        $member_recharge_card_order->payment_type = $payment_type;
        try {
            \DB::beginTransaction();
            $member_recharge_card_order->save();
            switch ($payment_type) {
                case "微信支付":
                    $params = Pay::wechat()->app([
                        'body' => "充值",
                        'out_trade_no' => $order_no,
                        'total_fee' => $money * 100,
                        'attach' => 2,
                    ])->getContent();
                    break;
                case "支付宝支付":
                    $params = Pay::alipay()->app([
                        'body' => "充值",
                        'out_trade_no' => $order_no,
                        'total_fee' => $money,
                        'passback_params' => 2,    //业务类型
                    ])->getContent();
                    break;
            }
            \DB::commit();
            return $this->renderJson(['payment_type' => $payment_type, 'params' => $params]);
        } catch (\Exception $exception) {
            \DB::rollBack();
            \Log::error($exception);

        }


    }

    // web购卡下单
    public function cardWebPay(Request $request)
    {
        $this->validate($request, [
            'store_id' => "required|numeric",
            "money" => "required",
            "payment_type" => "required",// 1，支付宝支付，2微信支付， 3，余额支付

        ], [
            "store_id.required" => "store_id不能为空",
            "store_id.numeric" => "store_id必须是数字",
            "money.required" => "money不能为空",
        ]);

        $order_no = Util::getOrderNum();
        $store_id = $request->input("store_id");
        $money = $request->input("money");
        $payment_type = $request->input("payment_type");

        $member_recharge_card_order = new MemberRechargeCardOrder();
        $member_recharge_card_order->order_no = $order_no;
        $member_recharge_card_order->member_id = Auth::id();
        $member_recharge_card_order->store_id = $store_id;
        $member_recharge_card_order->money = $money;
        $member_recharge_card_order->payment_type = $payment_type;
        try {
            \DB::beginTransaction();
            $member_recharge_card_order->save();
            switch ($payment_type) {
                case "微信支付":
                    $params = Pay::wechat()->wap([
                        'body' => "充值",
                        'out_trade_no' => $order_no,
                        'total_fee' => $money * 100,
                        'attach' => 4,
                    ])->getContent();
                    break;
                case "支付宝支付":
                    $params = Pay::alipay()->wap([
                        'body' => "充值",
                        'out_trade_no' => $order_no,
                        'total_fee' => $money,
                        'passback_params' => 4,    //业务类型
                    ])->getContent();
                    break;
            }
            \DB::commit();
            return $this->renderJson(['payment_type' => $payment_type, 'params' => $params]);
        } catch (\Exception $exception) {
            \DB::rollBack();
            \Log::error($exception);

        }
    }

    //endregion

    //region todo 微信支付回调
    public function wxnotify()
    {
        $wechat = pay::wechat();
        try {
            \DB::beginTransaction();
            $data = $wechat->verify();
            $callback = $data->all();
            \Log::info($callback);
            if ($callback['result_code'] === 'SUCCESS' && $callback['return_code'] === 'SUCCESS') {
                if ($callback['attach'] == 1 || $callback['attach'] == 3) {
                    //门店消费
                    $this->consume($data);
                } else {
                    // 购卡
                    $this->cardOrder($data);
                }


            }

            \DB::commit();
        } catch (\Exception $exception) {
            \DB::rollBack();
            \Log::error($exception);
        }
    }

    // endregion


    // region todo 支付宝支付

    public function alipayPayment()
    {

    }

    // endregion

    //region todo 门店 消费
    public function consume($data)
    {
        // 查找订单

        $member_order = MemberOrder::whereOrderNo($data['out_trade_no'])->where("is_pay", 0)->first();
        if (isset($member_order) && $data['total_fee'] == $member_order->money * 100) {

            $member_order->is_pay = 1;
            $member_order->pay_time = Carbon::now();
            $member_order->notify_pay = 1;

            // 分成
            try {
                \DB::beginTransaction();
                $member_order->save();
                $order = new MemberOrder();

                $order->memberPayCommission($member_order->store_id, $member_order->money, $member_order->id, $member_order->member_id);

                // todo 如果说有优惠金额扣除
                if ($member_order->coupon_money != 0 && $member_order != null) {
                    $member = Member::whereId($member_order->member_id)->first();
                    $member->decrement("card_money_coupon", $member_order->coupon_money);
                }

                \DB::commit();
                \Log::info("支付成功！");
            } catch (\Exception $exception) {
                \DB::rollBack();
                \Log::error($exception);
            }
        } else {
            \Log::error($data['out_trade_no'] . "订单不存在");
        }

    }


    //endregion


    //region todo 支付回调地址
    public function notify()
    {
        $store_id = 6;
        $money = 100;
        $member_order_id = 6;
        $member_id = 6;
        $member_order = new MemberOrder();
        try {
            \DB::beginTransaction();
            $member_order->memberPayCommission($store_id, $money, $member_order_id, $member_id);
            \DB::commit();
        } catch (\Exception $exception) {
            \DB::rollBack();
            \Log::error($exception);
            echo $exception;
        }

    }

    private function cardOrder($data)
    {

        try {
            \DB::beginTransaction();

            $order_no = $data['out_trade_no'];
            $orderService = new CardOrderService();
            $order = MemberRechargeCardOrder::where('order_no', $order_no)->where('is_pay', 0)->first();
            if ($order == null) {
                return 'FAIL';
            }
            $order->is_pay = 1;
            $order->pay_time = Carbon::now();
            $order->notify_pay = 1;
            $order->save();
            //判断是否有关系
            if (!StoreRecommendMember::where('member_id', $order->member_id)->first()) {
                \DB::table('store_recommend_member')->insert([
                    'member_id' => $order->member_id,
                    'store_id' => $order->store_id,
                    'created_at' => Carbon::now()
                ]);
            }

            $orderService->distribution($order);
            \DB::commit();
        } catch (\Exception $e) {
            \DB::rollBack();
            \Log::error($e);
            return 'FAIL';
        }
        return 'SUCCESS';
    }

    // endregion


}
